import wxApi from '@/common/js/wxApi'
import {
  domain
} from '@/common/js/config'
let Fly = require('flyio/dist/npm/wx')
let fly = new Fly()
var store = require('@/store/index.js')
var qs = require('qs')

var storageParam = null
/** 数据请求域名 */
fly.config.baseURL = domain
/** 接口请求拦截添加cachekey登录状态 */
fly.interceptors.request.use((request, response) => {
  // vuex 用作存储
  wxApi.loading(true)
  let vuxStore = store.default.state
  if (vuxStore.loginData) {
    request.body = prameFormData(request, vuxStore.loginData)
  } else {
    // 拦截当前接口发送数据,形成栈队列 ,往后排
    fly.lock()
    return wxLogin().then(res => {
      if (res.cacheKey) {
        request.body = prameFormData(request, vuxStore.loginData)
      }

      // 前一步拦截的接口,告知可以发起数据请求  必须返回request
      fly.unlock()
      return request
    })
  }
})
/** 数据回调状态处理 */
fly.interceptors.response.use((response, promise) => {
  wxApi.loading(false)
  console.log(response)

  if (response.data.code === 'success' || response.data.code === 'E00000') {
    return promise.resolve(response.data.data, response.data)
  } else if (response.data.code === 'failed') {
    store.default.commit('SET_LOGIN', null)
    if (response.data.message === '预约时间段错误') {
      return promise.resolve('预约时间段错误')
    }
    // return fly.request(response.request.url, storageParam, {
    //   method: response.request.method
    // })
  }
  wxApi.textToast(response.data.message)
  return false
}, (promise) => {
  wx.hideLoading()

  wx.showToast({
    title: '您的网络不给力！',
    icon: 'none'
  })

  return promise.resolve(undefined)
})
/** FormData  格式提交数据 */
function prameFormData (request, add) {
  if (request.method === 'POST') {
    storageParam = qs.stringify(Object.assign({}, request.body, {
      'cacheKey': add.cacheKey
    }))
    return storageParam
  }
  return request
}

/** 小程序获取code做登录 */
const wxLogin = () => {
  return new Promise((resolve, reject) => {
    wx.login({
      success (res) {
        wx.request({
          url: domain + '/Liteapp/Login',
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          data: {
            code: res.code
          },
          success (request) {
            let data = request.data.data
            store.default.commit('SET_LOGIN', data)

            if (data.hasBind === false) {
              wxApi.reLaunch('/pages/user/login')
            }
            getSystemInfo()
            wxGetUserInfo(resolve)
          },
          fail (err) {
            wxApi.textToast('登录接口异常')
            resolve(err)
          }
        })
      }

    })
  })
}

function wxGetUserInfo (resolve) {
  wx.getUserInfo({
    success (res) {
      resolve(store.default.state.loginData)
      if (store.default.state.loginData.isDownload === false) {
        savLiteappUserinfoSubscribe(Object.assign({}, res.userInfo, {
          cacheKey: store.default.state.loginData.cacheKey,
          unionid: 1

        }))
      }
      store.default.commit('SET_USERINFO', res.userInfo)
    },
    fail () {
      resolve(store.default.state.loginData)
    }

  })
}

function savLiteappUserinfoSubscribe (userInfo) {
  wx.request({
    url: domain + '/Liteapp/LiteappUserinfoSubscribe',
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    data: userInfo,
    success () {}

  })
}

function getSystemInfo () {
  wx.getSystemInfo({
    success: function (res) {
      store.default.commit('IS_IPHONEX', res.model.indexOf('iPhone X') !== -1)
    }

  })
}
export default fly
